import { useState, useMemo } from 'react';

declare type ModalType = 'add' | 'update';

export interface useModalConfig {
  defaultVisible?: boolean;
  defaultType?: ModalType;
}

export default function useModal(config: useModalConfig = {}) {
  const { defaultType = 'add', defaultVisible = false } = config;
  const [type, setType] = useState<ModalType>(defaultType);
  const [visible, setVisible] = useState<boolean>(defaultVisible);

  function toggle() {
    setVisible(!visible);
  }

  function setTypeWithVisible(val: ModalType) {
    setType(val);
    setVisible(true);
  }

  return useMemo(() => {
    return {
      type,
      setType,
      visible,
      setVisible,
      toggle,
      setTypeWithVisible,
    };
  }, [type, visible]);
}

